package com.relax.Semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

public class SemaphoreDemo {
    //创建一个信号量的实例，信号量初始值为0
    static Semaphore semaphore = new Semaphore(0);

    public static void main(String[] args) throws Exception {
        ExecutorService pool = Executors.newFixedThreadPool(3);
        pool.submit(()->{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("Thread1---start");
            //信号量加一
            semaphore.release();
        });

        pool.submit(()->{
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("Thread2---start");
            //信号量加一
            semaphore.release();
        });
        pool.submit(()->{
            System.out.println("Thread3---start");
            //信号量加一
            semaphore.release();
        });
        //等待两个子线程执行完毕就放过，必须要信号量等于2才放过
        semaphore.acquire(2);
        System.out.println("两个子线程执行完毕");

        //关闭线程池，正在执行的任务继续执行
        pool.shutdown();

    }
}
